package com.youbug.mall.auth.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youbug.common.constant.AuthServerConstant;
import com.youbug.common.exception.BizCodeEnum;
import com.youbug.common.to.UmsMemberTo;
import com.youbug.common.vo.R;
import com.youbug.mall.auth.feign.IAuthMemberFeignService;
import com.youbug.mall.auth.feign.IThirdPartFeignService;
import com.youbug.mall.auth.vo.UserLoginVo;
import com.youbug.mall.auth.vo.UserRegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.youbug.common.constant.AuthServerConstant.LOGIN_USER;

@Controller
public class MallLoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IThirdPartFeignService thirdPartFeignService;
    @Autowired
    private IAuthMemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R<Integer> sendCode(@RequestParam("phone") String phone) {

        //1、接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            //活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000) {
                //60s内不能再发
                return R.fail(BizCodeEnum.SMS_CODE_EXCEPTION.getCode().intValue(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        //2、验证码的再次效验 redis.存key-phone,value-code
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();

        //存入redis，防止同一个手机号在60秒内再次发送验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,
                redisStorage,10, TimeUnit.MINUTES);
        // 不实际发送验证码
//        thirdPartFeignService.sendCode(phone, codeNum);

        return R.ok(code);
    }

    @PostMapping(value = "/mall/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result,
                           RedirectAttributes attributes) {

        //如果有错误回到注册页面
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors", errors);

            //效验出错回到注册页面
            return "redirect:http://auth.gulimall.com/mall/reg.html";
        }

        //1、效验验证码
        String code = vo.getCode();

        //获取存入Redis里的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            //截取字符串
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码;令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vo.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                R<String> register = memberFeignService.register(vo);
                if (register.getCode() == R.SUCCESS) {
                    //成功
                    return "redirect:http://auth.gulimall.com/mall/login.html";
                } else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData());
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/mall/reg.html";
                }
            } else {
                //效验出错回到注册页面
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/mall/reg.html";
            }
        } else {
            //效验出错回到注册页面
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/mall/reg.html";
        }
    }

    @PostMapping(value = "/mallLogin")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) throws JsonProcessingException {

        //远程登录
        R<UmsMemberTo> login = memberFeignService.login(vo);

        if (login.getCode() == R.SUCCESS) {
            UmsMemberTo member = login.getData();
            session.setAttribute(LOGIN_USER, member);
            ObjectMapper mapper = new ObjectMapper();
            stringRedisTemplate.opsForValue().set(LOGIN_USER+":"+member.getId(), mapper.writeValueAsString(member));
            return "redirect:http://gulimall.com";
        } else {
            Map<String,String> errors = new HashMap<>();
            errors.put("msg", login.getMsg());
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/mall/login.html";
        }
    }

    @GetMapping(value = "/mall/login.html")
    public String loginPage() {

        return "login";
    }

    @GetMapping(value = "/mall/reg.html")
    public String regPage() {

        return "reg";
    }

}
